#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/11/28 0:04
# @Author : 詹荣瑞
# @File : document.py
# @desc : 本代码未经授权禁止商用
import bonetex.command as c


class Environment(object):

    def __init__(self, name):
        self.name = name
        self.begin = c.begin(name)
        self.end = c.end(name)
        self.contents = []

    def latex(self, indent=""):
        next_indent = indent + "  "
        contents = map(lambda _: _.latex(next_indent), self.contents)
        out = indent + self.begin.latex()
        out += "".join(contents)
        out += indent + self.end.latex()
        return out


class Section(object):

    def __init__(self, name):
        self.name = name
        self.contents = [c.section(name)]

    def latex(self, indent=""):
        contents = map(lambda _: _.latex(indent), self.contents)
        out = "".join(contents)
        return out

    def append(self, *contents):
        for content in contents:
            self.contents.append(content)
        return self


class Document(object):

    def __init__(self, document_class="article", document_option=None):
        if document_option is None:
            document_option = {}
        self.header = [c.document_class(document_class, **document_option)]
        self.body = Environment("document")

        # 方法别名
        self.pre_append = self.pre_append
        self.body_append = self.body_append

    def use(self, func):
        if func == "math":
            self.header.append(c.use_package("array"))
            self.header.append(c.use_package("amsmath"))

    def latex(self):
        contents = map(lambda _: _.latex(), self.header)
        out = "".join(contents)
        out += self.body.latex()
        return out

    def pre_append(self, *contents):
        for content in contents:
            self.header.append(content)
        return self

    def body_append(self, *contents):
        for content in contents:
            self.body.contents.append(content)
        return self
